package org.zoomdev.zoom.aop.factory.impl;

import org.zoomdev.zoom.common.exceptions.ZoomException;
import org.zoomdev.zoom.common.utils.Classes;

import java.lang.reflect.Type;

public abstract class AsmSingleMethodFactory<T, E> extends BaseSingleMethodFactory<T, E> {

    protected final ClassLoader classLoader;
    protected final Class<T> interfaceClass;


    public AsmSingleMethodFactory(ClassLoader classLoader) {
        this.classLoader = classLoader;
        Type tt = Classes.getAllParameterizedTypes(getClass())[0];
        if (tt instanceof Class) {
            this.interfaceClass = (Class<T>) tt;
        } else {
            throw new ZoomException("第一个泛型参数" + tt + "不是Class");
        }
    }


    protected Class<?> createClass(String className, E param) {
        return AsmClassloader.defineClass(className, createBytes(className.replace('.', '/'), param));
    }


    protected abstract byte[] createBytes(String className, E param);


    @Override
    protected T createImpl(E param) {
        String className = getClassName(param);
        Class<?> clazz;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            clazz = createClass(className, param);
        }
        return (T) Classes.newInstance(clazz);
    }


    protected abstract String getClassName(E param);

}
